# coding: utf-8

import datetime, sys, SocketServer,time
import tornado.httpserver
import tornado.ioloop
from tornado.options import define, options
import tornado.web
import tornado.database
import tornado.escape
import gearman
import urlparse
import urllib
import re
import gzip,zlib
from cStringIO import StringIO
import json
import binascii
import iso8601

reload (sys)
sys.setdefaultencoding('utf-8')

log_folder = "/var/log/app_beacon_sdk"
client = gearman.GearmanClient(["localhost:4730"])

class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
                (r"/qyer/v0[/]*", AppHandler)
                ]
        settings = dict(
                debug = False,
                )
        tornado.web.Application.__init__(self, handlers, **settings)



#class BaseHandler(tornado.web.RequestHandler):
#    def __init__( self, *args, **kwargs ):
#        # 继承于 tornado.web.RequestHandler
#        tornado.web.RequestHandler.__init__( self, *args, **kwargs )
 

class AppHandler(tornado.web.RequestHandler):

    def post(self):
        successful = False
        try:
            self.client = gearman.GearmanClient(["localhost:4730"])
            self.today = datetime.datetime.today()
            self.did = self.get_argument("did", default = "")
            self.uid = self.get_argument("uid", default = 0)
            self.debug = self.get_argument("debug", default = "false")
            self.ins_time = self.get_argument("ins_time",default=0)
            self.raw_ = self.get_argument("raw", default = "")
            #print "raw:%s" % (self.raw_)
            try:
                if re.search(r"<([\w\W]+)>",self.raw_):
                    self.raw_hex = re.search(r"<([\w\W]+)>",self.raw_).group(1).replace(" ","").decode("hex")
                else:
                    self.raw_hex = self.raw_.decode("hex")
                    #self.raw_hex = '1f8b08000000000000000bc9c82c5600a2c2cad4228594c4924485e4d4bc92d4223d000b17aa0319000000'.decode("hex")
                #print self.raw_hex
                fio = StringIO(self.raw_hex)
                self.raw_json = gzip.GzipFile(fileobj=fio).read()
                #self.raw_json = zlib.decompressobj(self.get_argument("raw", default = ""))
                #self.raw_json = zlib.decompress(self.get_argument("raw", default = ""))
                #self.raw = tornado.escape.json_decode(self.raw_json)
            except Exception,e:
                print e
                self.write(json.dumps({"successful":"false",'error':'decompress : %s' % e}))
                return 
            self.raw = tornado.escape.json.loads(self.raw_json)
            #时间修改为服务器时间
            self.timestamp = int(time.time())
        
          
            for data in self.raw:
                #print data
                self.v = data.get("v", "")
                self.beacon_type_id=1
                if self.v != "":
                    self.beacon_type_id=2
                self.path = data.get("p","")
                self.referer = data.get('r',"")
                self.time = data.get('t',"")
                '''if re.search(r"T",self.time):
                    print self.time
                    self.time = int(time.mktime(iso8601.parse_date(self.time).timetuple()))
                    print self.time'''
                self.lat = data.get('lat',"")
                self.lon = data.get('lon',"")
                self.client_id = data.get('client_id',"")
                self.track_app_version = data.get('track_app_version',"")
                self.other = data.get("e","")

                self.record = [self.uid, self.did, self.timestamp, self.ins_time, self.beacon_type_id, self.path, self.referer, self.v, self.time, self.lat, self.lon, self.client_id, self.track_app_version, self.other]
                #print self.record
                if self.debug == "true":
                    self.data_file2 = "%s/test_%04d-%02d-%02d-%02d.log" % (log_folder, self.today.year, self.today.month, self.today.day, self.today.hour)
                else:
                    self.data_file2 = "%s/log_%04d-%02d-%02d-%02d.log" % (log_folder, self.today.year, self.today.month, self.today.day, self.today.hour)
                #print self.data_file2
                self.client.submit_job("app_beacon", "%s###%s" % (self.data_file2, "#|~".join(map(str, self.record))), background=True)
                successful = True
                

        except Exception,e:
            print e
            self.writeErrorLog("POST = %s" % (e))
            self.writeLog("Exception type = %s" % (sys.exc_type))
            self.writeLog("Exception = %s" % (sys.exc_value))
            self.writeLog("Exception Trace= %s" % (sys.exc_traceback))
            self.write(json.dumps({"successful":"False",'error':'Final : %s' % e}))
        #self.set_status(204)
        if successful:
            self.write(json.dumps({"successful":"true"}))
        self.finish()

    def get(self):
        try:
            pass

        except:
            pass

    def writeLog(self, message, log_file = "{0}/error_log".format(log_folder)):
        line = "[%s] %s\n" % (datetime.datetime.now(), message)
        with open(log_file, 'aw') as f:
            f.write(line)

    def writeErrorLog(self, message, log_file = "{0}/error_log.log".format(log_folder)):
        line = "[%s] %s\n" % (datetime.datetime.now(), message)
        with open(log_file, 'w') as f:
            f.write(line)

def main(argv):
    tornado.options.parse_command_line()
    http_server = tornado.httpserver.HTTPServer(Application(), xheaders=True)
    http_server.listen(int(argv[1]))
    tornado.ioloop.IOLoop.instance().start()
    print "start listening..."

if __name__ == "__main__":
    main(sys.argv)

